<template>
  <BasicDrawer
    v-bind="$attrs"
    :title="getTitle"
    @register="registerDrawer"
    width="50%"
    showFooter
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>

<script setup lang="ts">
  import { computed, ref, unref } from 'vue';
  import { formSchema } from './data';
  import { useMessage } from '@/hooks/web/useMessage';
  import { getOpManufacturerTypeApi, addOpManufacturerTypeApi, editOpManufacturerTypeApi } from '@/api/operations/manufacturertype.api';
  import { BasicForm, useForm } from '@/components/Form';
  import { OpManufacturerTypeIM } from '@/model/operations/manufacturertype.model';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();
  const isUpdate = ref(true);

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ loading: true, confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      const info = await getOpManufacturerTypeApi(data.record.id);
      setFieldsValue({...info});
    }
    setDrawerProps({ loading: false });
  });

  /** 标题初始化 */
  const getTitle = computed(() => (!unref(isUpdate) ? '新增资产分类' : '编辑资产分类'));

  /** 提交按钮 */
  async function handleSubmit() {
    try {
      const values: OpManufacturerTypeIM = await validate();
      setDrawerProps({ confirmLoading: true });
      unref(isUpdate)
        ? await editOpManufacturerTypeApi(values).then(() => {
            closeDrawer();
            createMessage.success('编辑资产分类成功！');
          })
        : await addOpManufacturerTypeApi(values).then(() => {
            closeDrawer();
            createMessage.success('新增资产分类成功！');
          });
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
